var express = require('express');
var path = require('path')
var fs = require('fs')
var db = require('../../../tools/database')
var util = require('../../../tools/util')
var ejs = require('ejs')
var router = express.Router();

function getLabelSet(result, labelGenerator){
    let labelSet = ''
    result.forEach(item => {
        let itemStatus = ''
        if(item.OnSale){
            itemStatus = `在售${item.ItemID}`
        }else{
            itemStatus = `下架${item.ItemID}`
        }
        labelSet += labelGenerator({
            itemID: item.ItemID,
            itemName: item.ItemName,
            itemStatus: itemStatus,
            onSale: item.OnSale? true: false
        })
    });
    return labelSet
}

// 获取用户发布的商品标签
router.use(function (req, res, next) {
	// 验证 token, 获取用户名
    util.jwtVerify(req, res, (decoded)=>{
        var userName = decoded.userName
        console.log(userName)
        let sql = `SELECT * FROM Items WHERE UserName=? ORDER BY ItemID DESC`
        // 查询、返回
        db.queryCallback(sql, [userName], res, (result)=>{
            let modelPath = path.join(__dirname, './myhome/H_HomeItemLabel.ejs')
            let labelGenerator = ejs.compile(fs.readFileSync(modelPath, 'utf-8'));
            let labelSet = getLabelSet(result, labelGenerator)
            util.dataRespond(labelSet, res)
        }, false, false)
    })
});


module.exports = router;